﻿/*
 * @author Lee 
 * Time: 20180403 
 * Abstract: SharePoint API的二次封装
 */

using System;
using Microsoft.SharePoint;

namespace SharePointHelper.DLL.SSOM
{
	public class Feature
	{
        #region 通过feature name获取feature
        /// <summary>
        /// 通过feature name获取feature
        /// </summary>
        /// <param name="featureName"></param>
        /// <returns></returns>
        public static Microsoft.SharePoint.Administration.SPFeatureDefinition GetFeature(string featureName)
		{
			Microsoft.SharePoint.Administration.SPFeatureDefinition feature = null;
			try
			{
				// 初始化
				if (string.IsNullOrEmpty(featureName)) { throw new Exception("Feature name passed is null"); }
				featureName = featureName.ToLower();
				System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo(1033);

				foreach (Microsoft.SharePoint.Administration.SPFeatureDefinition f in Microsoft.SharePoint.Administration.SPFarm.Local.FeatureDefinitions)
				{
					if (f.GetTitle(cultureInfo).ToLower() == featureName || (!string.IsNullOrEmpty(f.DisplayName) && f.DisplayName.ToLower() == featureName))
					{
						feature = f;
						break;
					}
				}
			}
			catch (Exception ex)
			{
				Log.WriteError("xdgfhcgjtfdzstdzsdfgv", ex, "feature: " + featureName);
			}
			return feature;
		}
        #endregion

        #region 激活一个web scope的feature
        /// <summary>
        /// 激活一个web scope的feature 
        /// 如果重复的已经存在，则跳过
        /// </summary>
        /// <param name="web"></param>
        /// <param name="featureId"></param>
        /// <param name="isSave"></param>
        /// <returns></returns>
        public static bool ActivateFeature(SPWeb web, Guid featureId, bool isSave)
		{
			bool isSuccessful = false;
			try
			{
				// init
				if (web == null) { throw new Exception("SPWeb passed is null"); }
				if (featureId == null || featureId == Guid.Empty) { throw new Exception("FeatureId GUID passed is null or empty"); }


				bool isMatch = false;
				foreach (SPFeature feature in web.Features)
				{
					if (feature.DefinitionId == featureId) { isMatch = true; }
				}
				if (!isMatch) { web.Features.Add(featureId); }
				else if (isSave) { isSave = false; }

				// save
				if (isSave) { web.Update(); }

				// assume success
				isSuccessful = true;
			}
			catch (Exception ex)
			{
				Log.WriteError("r85yftydsrserwer", ex, "featureId: " + featureId);
				isSuccessful = false;
			}
			return isSuccessful;
		}
	}
    #endregion
}
